package com.yylending.las.lending.outlet;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.Loader;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.tbruyelle.rxpermissions.Permission;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yylending.las.Constants;
import com.yylending.las.Global;
import com.yylending.las.R;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.common.location.LocationPresenter;
import com.yylending.las.common.location.entity.Location;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.lending.QuotaEvent;
import com.yylending.las.lending.process.confirmloan.ConfirmLoanModel;
import com.yylending.las.lending.process.confirmloan.ConfirmLoanPresenter;
import com.yylending.las.lending.quota.idcard.IdCardModel;
import com.yylending.las.lending.quota.myquota.MyQuotaModel;
import com.yylending.las.webview.WebViewActivity;

/**
 * 门店方案
 * Created by laixj on 2018/1/8.
 * Copyright ©2016 www.yylending.com. All Rights Reserved.
 */
public class OutletAppointActivity extends BaseActivity implements ConfirmLoanPresenter.View, LocationPresenter.View {

	private final static int LOADER_ID_CONFIRM_LOAN = 1;
	private final static int LOADER_ID_LOCATE = 2;
	static final String ARG_APPLY_STATUS = "arg_apply_status";

	@BindView(R.id.submit_btn)
	Button mSubmitBtn;
	@BindView(R.id.top_hint_tv)
	TextView mTopHintTv;
	@BindView(R.id.support_bank_tv)
	TextView mSupportBankTv;
	@BindView(R.id.house_property_ll)
	LinearLayout mHousePropertyLl;
	@BindView(R.id.imageView)
	ImageView mImageView;
	@BindView(R.id.taxes_ll)
	LinearLayout mTaxesLl;
	@BindView(R.id.policy_ll)
	LinearLayout mPolicyLl;
	@BindView(R.id.accumulation_fund_ll)
	LinearLayout mAccumulationFundLl;
	@BindView(R.id.social_security_ll)
	LinearLayout mSocialSecurityLl;

	private ConfirmLoanPresenter mConfirmLoanPresenter;
	private LocationPresenter mLocationPresenter;

	/**
	 * 定位信息
	 */
	private Location mLocation;
	/**
	 * 是否需要在定位成功之后自动预约门店
	 */
	private boolean mAutoCommit;

	MyQuotaModel.ApplyStatus mApplyStatus;
	/**
	 * 提示Dialog
	 */
	private CommonDialog mNoticeDialog;

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_CONFIRM_LOAN:
				mConfirmLoanPresenter = (ConfirmLoanPresenter) data;
				mConfirmLoanPresenter.attach(this);
				break;
			case LOADER_ID_LOCATE:
				mLocationPresenter = (LocationPresenter) data;
				mLocationPresenter.attach(this);
				PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
				break;
			default:
				break;
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_CONFIRM_LOAN:
				return new PresenterLoader<>(this, new ConfirmLoanPresenter.Generator());
			case LOADER_ID_LOCATE:
				return new PresenterLoader<>(this, new LocationPresenter.Generator());
			default:
				return null;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_outlet_appoint);
		ButterKnife.bind(this);
		setTitle(R.string.outlet_program);

		mApplyStatus = getIntent().getParcelableExtra(ARG_APPLY_STATUS);

		String text = mTopHintTv.getText().toString();
		SpannableStringBuilder builder = new SpannableStringBuilder(text);
		ForegroundColorSpan redSpan = new ForegroundColorSpan(getResources().getColor(R.color.color_4b7cf9));
		ForegroundColorSpan redSpan1 = new ForegroundColorSpan(getResources().getColor(R.color.color_4b7cf9));
		builder.setSpan(redSpan, 15, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		builder.setSpan(redSpan1, 19, 22, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

		mTopHintTv.setHighlightColor(getResources().getColor(android.R.color.transparent));
		mTopHintTv.setText(builder);
		mTopHintTv.setMovementMethod(LinkMovementMethod.getInstance());

		getSupportLoaderManager().initLoader(LOADER_ID_CONFIRM_LOAN, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_LOCATE, null, this);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		dismissNoticeDialog();
		getSupportLoaderManager().destroyLoader(LOADER_ID_CONFIRM_LOAN);
		getSupportLoaderManager().destroyLoader(LOADER_ID_LOCATE);
		super.onDestroy();
	}

	public static void start(Activity activity, MyQuotaModel.ApplyStatus status) {
		Intent intent = new Intent(activity, OutletAppointActivity.class);
		intent.putExtra(ARG_APPLY_STATUS, status);
		activity.startActivity(intent);
	}

	@OnClick({R.id.submit_btn, R.id.support_bank_tv, R.id.house_property_ll, R.id.taxes_ll, R.id.policy_ll, R.id.accumulation_fund_ll, R.id.social_security_ll})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.submit_btn:
				//预约门店
				appointOutlet();
				break;
			case R.id.support_bank_tv:
				WebViewActivity.start(this, Global.BASE_URL + Global.SUPPORT_BANK_LIST_URL, getString(R.string.support_bank_list), "");
				break;
			case R.id.house_property_ll:
				showNoticeDialog(R.layout.dialog_house_property);
				break;
			case R.id.taxes_ll:
				showNoticeDialog(R.layout.dialog_taxes);
				break;
			case R.id.policy_ll:
				showNoticeDialog(R.layout.dialog_policy);
				break;
			case R.id.accumulation_fund_ll:
				showNoticeDialog(R.layout.dialog_accumulation_fund);
				break;
			case R.id.social_security_ll:
				showNoticeDialog(R.layout.dialog_social_security);
				break;
		}
	}

	private void showNoticeDialog(int layoutId) {
		if (null != mNoticeDialog){
			mNoticeDialog.dismiss();
			mNoticeDialog = null;
		}
		mNoticeDialog = new NoticeDialog(this, getString(R.string.apply_requirement), true, layoutId);
		mNoticeDialog.show();
	}

	private void dismissNoticeDialog() {
		if (mNoticeDialog != null && mNoticeDialog.isShowing()) {
			mNoticeDialog.dismiss();
			mNoticeDialog = null;
		}
	}

	/**
	 * 申请材料弹框
	 * Created by laixj on 2018/1/9.
	 * Copyright ©2016 www.yylending.com. All Rights Reserved.
	 */
	public class NoticeDialog extends CommonDialog {

		public NoticeDialog(@NonNull Context context, String title, boolean cancelAble, int layoutId) {
			super(context, title, cancelAble, layoutId);
		}

		@Override
		public void show() {
			Window dialogWindow = getWindow();
			WindowManager.LayoutParams lp = dialogWindow.getAttributes();
			dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP);
			//lp.x = 100; // 新位置X坐标
			//按比例设置距离顶部的高度
			int y = (int)(306 / 1280.0f * getResources().getDisplayMetrics().heightPixels);
			lp.y = y;//新位置Y坐标
			dialogWindow.setAttributes(lp);
			super.show();
		}
	}

	/**
	 * 预约门店
	 */
	private void appointOutlet() {
		mSubmitBtn.setEnabled(false);
		if (null == mLocation) {
			mAutoCommit = true;
			PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
		} else {
			mAutoCommit = false;
			showLoading(false);
			confirmLoan();
		}
	}

	/**
	 * 线下借款提交
	 */
	private void confirmLoan() {
		mConfirmLoanPresenter.confirmLoan("36", "0", String.valueOf(mLocation.longitude), String.valueOf(mLocation.latitude), Constants.LOAN_OUTLET);
	}

	@Override
	public void onFunctionalCompleted(boolean autoTips) {
		super.onFunctionalCompleted(autoTips);
		dismissLoading();
	}

	@Override
	public void confirmLoanSuccess(ConfirmLoanModel.ConfirmLoan confirmLoan) {
		mSubmitBtn.setEnabled(true);
		OutletActivity.start(this);
		finish();
	}

	@Override
	public void confirmLoanFailure(String tips) {
		showToast(tips);
		mSubmitBtn.setEnabled(true);
	}

	@Override
	public void confirmLoanRepeat(String tips) {
		showToast(tips);
		EventAgent.post(new QuotaEvent.RefreshStatusEvent(QuotaEvent.Event.QUOTA_REFRESH, null));
	}

	@Override
	public void creditReportingOutdated() {
		showToast(R.string.credit_report_outdated);
		// 征信过期 重新获取额度状态
		finish();
	}

	@Override
	public void getIdCardSuccess(IdCardModel.IdCard idCard) {

	}

	@Override
	public void getIdCardFailure(String s) {

	}

	@Override
	public void onLocateSuccess(Location location) {
		mLocation = location;
		if (mAutoCommit)
			confirmLoan();
	}

	@Override
	public void onLocateFail(boolean noPermission) {
		if (mAutoCommit) {
			dismissLoading();
			mAutoCommit = false;
			showToast(R.string.locate_need_retry);
			mSubmitBtn.setEnabled(true);
		}
	}

	@Override
	public void showDialog() {

	}

	@Override
	public void dismissDialog() {

	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		switch (functionalCode) {
			case ConfirmLoanModel.METHOD_CONFIRM_LOAN:
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						showToast(R.string.network_need_retry);
						mSubmitBtn.setEnabled(true);
					}
				});
				break;
		}
	}

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				case Manifest.permission.ACCESS_COARSE_LOCATION:
					if (permission.granted) {
						if (mAutoCommit) {
							showLoading(false);
						}
						mLocationPresenter.startLocation(false);
					} else {
						if (mAutoCommit) {
							dismissLoading();
						}
						showNeedPermission(getString(R.string.location_right_hint, getString(R.string.app_name)));
					}
					break;
				default:
					break;
			}

		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {

		}
	};

	private void showNeedPermission(String msg) {
		showOneBtnDialog(msg, getString(R.string.got_it));
	}
}